import * as vscode from 'vscode'
import { RecordService } from '../services/recordService'
import { CommentService } from '../services/commentService'
import { DetailPanelService } from '../services/detailPanelService'
import { showRecordForm } from '../ui/forms/recordForm'
import RecordViewProvider from '../providers/recordViewProvider'
import { COMMANDS } from '../constants/commands'

export class RecordCommands {
  constructor(
    private context: vscode.ExtensionContext,
    private recordService: RecordService,
    private commentService: CommentService,
    private detailPanelService: DetailPanelService,
    private recordViewProvider: RecordViewProvider
  ) {}

  // 新增问题记录命令
  async createRecordCommand(): Promise<void> {
    console.log('新增问题记录命令被调用')

    const editor = vscode.window.activeTextEditor
    if (!editor) {
      vscode.window.showWarningMessage('请先打开一个文件')
      return
    }

    const selection = editor.selection
    const codeSnippet = editor.document.getText(selection)
    const filePath = editor.document.fileName
    const lineRange = `${selection.start.line + 1}-${selection.end.line + 1}`

    console.log('代码片段:', codeSnippet)
    console.log('文件路径:', filePath)
    console.log('行范围:', lineRange)

    const context = {
      filePath,
      codeSnippet,
      lineRange
    }

    try {
      const recordData = await showRecordForm(context)
      console.log('表单返回数据:', recordData)

      if (recordData && recordData.problem && recordData.solution) {
        const record = this.recordService.createRecord(recordData)
        await this.recordService.saveRecord(record)

        this.recordViewProvider.updateRecords(this.recordService.getWorkspaceRecords())

        vscode.window.showInformationMessage('问题记录已保存！如需添加代码注释，请点击生成注释按钮。')
      } else {
        console.log('表单数据无效或用户取消:', recordData)
      }
    } catch (error) {
      console.error('记录过程中出错:', error)
      vscode.window.showErrorMessage('记录失败: ' + error)
    }
  }

  // 打开问题记录视图
  openRecordView(): void {
    vscode.commands.executeCommand(COMMANDS.FOCUS_RECORDS_VIEW)
  }

  // 显示记录详情
  recordDetail(recordId: number): void {
    const record = this.recordService.findRecord(recordId)
    if (record) {
      this.detailPanelService.showRecordDetail(record)
    }
  }

  // 删除问题记录 - 增强版本
  async deleteRecord(recordId: number): Promise<void> {
    const record = this.recordService.findRecord(recordId)
    if (!record) {
      vscode.window.showErrorMessage('记录不存在')
      return
    }

    const result = await vscode.window.showWarningMessage(
      `确定要删除记录 #${recordId} 吗？这将同时删除代码中的注释。`,
      { modal: true },
      '确定',
      '只删除记录（保留注释）'
    )

    if (result === '确定') {
      try {
        // 删除记录（会自动保存文件）
        await this.recordService.deleteRecord(recordId)

        // 尝试删除注释
        try {
          await this.commentService.deleteRecordComment(recordId, record.filePath)
        } catch (commentError) {
          console.warn('删除注释时出现问题:', commentError)

          // 如果删除失败，提供手动清理选项
          const cleanupChoice = await vscode.window.showWarningMessage(
            '注释删除可能不完整，是否进行文件注释清理？',
            '清理所有CodeMemo注释',
            '跳过'
          )

          if (cleanupChoice === '清理所有CodeMemo注释') {
            const removedCount = await this.commentService.cleanupAllComments(record.filePath)
            vscode.window.showInformationMessage(`已清理 ${removedCount} 条注释`)
          }
        }

        // 关闭详情页
        this.detailPanelService.closeRecordDetailPanel(recordId)

        // 刷新视图
        this.recordViewProvider.updateRecords(this.recordService.getWorkspaceRecords())

        vscode.window.showInformationMessage('记录已删除，文件已自动保存!')
      } catch (error) {
        console.error('删除记录失败:', error)
        vscode.window.showErrorMessage('删除失败: ' + error)
      }
    } else if (result === '只删除记录（保留注释）') {
      // 只删除记录，不删除注释
      await this.recordService.deleteRecord(recordId)
      this.detailPanelService.closeRecordDetailPanel(recordId)
      this.recordViewProvider.updateRecords(this.recordService.getWorkspaceRecords())
      vscode.window.showInformationMessage('记录已删除（注释已保留）')
    }
  }

  // 新增：清理文件注释的独立命令
  async cleanupFileComments(): Promise<void> {
    const editor = vscode.window.activeTextEditor
    if (!editor) {
      vscode.window.showWarningMessage('请先打开一个文件')
      return
    }

    const filePath = editor.document.fileName

    const result = await vscode.window.showWarningMessage('确定要清理当前文件中的所有CodeMemo注释吗？', { modal: true }, '确定')

    if (result === '确定') {
      try {
        const removedCount = await this.commentService.cleanupAllComments(filePath)
        if (removedCount > 0) {
          vscode.window.showInformationMessage(`已清理 ${removedCount} 条CodeMemo注释`)
        } else {
          vscode.window.showInformationMessage('未找到需要清理的注释')
        }
      } catch (error) {
        console.error('清理注释失败:', error)
        vscode.window.showErrorMessage('清理失败: ' + error)
      }
    }
  }

  // 更新记录引用位置
  async updateRecordReference(recordId: number): Promise<void> {
    const record = this.recordService.findRecord(recordId)
    if (!record) {
      vscode.window.showErrorMessage('记录不存在')
      return
    }

    try {
      // 读取文件内容
      const document = await vscode.workspace.openTextDocument(record.filePath)
      const fileText = document.getText()

      // 查找代码片段的匹配位置
      const newRange = this.findCodeSnippetInFile(fileText, record.codeSnippet)

      if (!newRange) {
        vscode.window.showWarningMessage('在文件中未找到匹配的代码片段')
        return
      }

      // 更新记录的行范围
      const newLineRange = `${newRange.startLine}-${newRange.endLine}`
      const updatedRecord = await this.recordService.updateRecord(recordId, {
        lineRange: newLineRange
      })

      if (updatedRecord) {
        // 刷新视图
        this.recordViewProvider.updateRecords(this.recordService.getWorkspaceRecords())
        vscode.window.showInformationMessage(`引用位置已更新: ${newLineRange}`)
      }
    } catch (error) {
      console.error('更新引用位置失败:', error)
      vscode.window.showErrorMessage('更新引用位置失败: ' + error)
    }
  }

  // 在文件中查找代码片段
  private findCodeSnippetInFile(fileText: string, codeSnippet: string): { startLine: number; endLine: number } | null {
    // 清理空白字符，便于匹配
    const cleanSnippet = codeSnippet.trim()
    if (!cleanSnippet) return null

    const fileLines = fileText.split('\n')
    const snippetLines = cleanSnippet.split('\n').map(line => line.trim())

    // 逐行搜索匹配
    for (let i = 0; i <= fileLines.length - snippetLines.length; i++) {
      let isMatch = true

      // 检查从当前行开始的连续行是否匹配
      for (let j = 0; j < snippetLines.length; j++) {
        const fileLine = fileLines[i + j]?.trim() || ''
        const snippetLine = snippetLines[j]

        if (fileLine !== snippetLine) {
          isMatch = false
          break
        }
      }

      if (isMatch) {
        return {
          startLine: i + 1, // VSCode 行号从1开始
          endLine: i + snippetLines.length
        }
      }
    }

    return null
  }

  // 生成注释命令
  async generateComment(recordId: number): Promise<void> {
    const record = this.recordService.findRecord(recordId)
    if (!record) {
      vscode.window.showErrorMessage('记录不存在')
      return
    }

    try {
      // 检查是否已有注释
      const hasComment = await this.commentService.hasRecordComment(recordId, record.filePath)

      if (hasComment) {
        vscode.window.showInformationMessage(`记录 #${recordId} 已有注释，无需重复生成`)
        return
      }

      // 生成注释
      await this.commentService.insertRecordComment(record)
      vscode.window.showInformationMessage('注释已生成，文件已自动保存!')
    } catch (error) {
      console.error('生成注释失败:', error)
      vscode.window.showErrorMessage('生成注释失败: ' + error)
    }
  }

  // 显示面板状态（调试用）
  showPanelStatus(): void {
    const info = this.detailPanelService.getPanelModeInfo()

    const modeText = info.allowMultiple ? '多开模式' : '单开模式'
    const statusText = `面板模式: ${modeText}\n当前打开: ${info.currentCount} 个\n面板ID: [${info.panelIds.join(', ')}]`

    vscode.window.showInformationMessage(statusText)
    console.log('=== 面板状态 ===')
    console.log(statusText)
    console.log('===============')
  }
}
